<template>
    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="workflow-form"
    >
        <!-- 名称 -->
        <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入工作流名称" />
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="描述" prop="description">
            <el-input
                v-model="formData.description"
                type="textarea"
                rows="3"
                placeholder="请输入工作流描述"
            />
        </el-form-item>

        <!-- 分类 -->
        <el-form-item label="分类" prop="category">
            <el-select v-model="formData.category" placeholder="请选择分类">
                <el-option label="人物" value="人物" />
                <el-option label="场景" value="场景" />
                <el-option label="物品" value="物品" />
                <el-option label="其他" value="其他" />
            </el-select>
        </el-form-item>

        <!-- 标签 -->
        <el-form-item label="标签" prop="tags">
            <el-tag
                v-for="tag in formData.tags"
                :key="tag"
                closable
                @close="handleRemoveTag(tag)"
            >
                {{ tag }}
            </el-tag>
            <el-input
                v-if="inputVisible"
                ref="tagInputRef"
                v-model="inputValue"
                class="tag-input"
                size="small"
                @keyup.enter="handleInputConfirm"
                @blur="handleInputConfirm"
            />
            <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
        </el-form-item>

        <!-- 预览图 -->
        <el-form-item label="预览图" prop="thumbnail">
            <el-upload
                class="thumbnail-uploader"
                :action="null"
                :auto-upload="false"
                :show-file-list="false"
                accept="image/*"
                @change="handleThumbnailChange"
            >
                <img v-if="formData.thumbnail" :src="formData.thumbnail" class="thumbnail" />
                <el-icon v-else class="thumbnail-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="form-help">建议上传正方形图片作为工作流预览图</div>
        </el-form-item>

        <!-- 工作流配置 -->
        <el-form-item label="工作流配置" prop="comfyuiJson">
            <div class="json-editor">
                <el-button class="import-btn" @click="jsonImportVisible = true">
                    导入 JSON
                </el-button>
                <el-input
                    v-model="jsonInput"
                    type="textarea"
                    rows="10"
                    placeholder="请输入或导入 ComfyUI 工作流配置 JSON"
                    @input="handleJsonInput"
                />
            </div>
            <div v-if="jsonError" class="json-error">
                {{ jsonError }}
            </div>
        </el-form-item>

        <!-- 发布设置 -->
        <el-form-item label="发布设置">
            <el-switch
                v-model="formData.isPublic"
                active-text="公开"
                inactive-text="私有"
            />
        </el-form-item>

        <!-- 版本号 -->
        <el-form-item label="版本号" prop="version">
            <el-input v-model="formData.version" placeholder="例如: 1.0.0" />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
            <el-button type="primary" @click="handleNext">下一步</el-button>
            <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, watch } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { WorkflowTemplate } from '@/types';

const props = defineProps<{
    workflow?: Partial<WorkflowTemplate>;
}>();

const emit = defineEmits<{
    (e: 'next', data: Partial<WorkflowTemplate>): void;
    (e: 'cancel'): void;
}>();

const formRef = ref<FormInstance>();
const formData = ref<Partial<WorkflowTemplate>>({
    name: '',
    description: '',
    category: '',
    tags: [],
    thumbnail: '',
    comfyuiJson: null,
    isPublic: false,
    version: '1.0.0',
    rows: 10,
    params: []
});

// JSON 相关状态
const jsonInput = ref('');
const jsonError = ref('');
const jsonImportVisible = ref(false);

// 标签输入相关状态
const inputVisible = ref(false);
const inputValue = ref('');
const tagInputRef = ref<HTMLInputElement>();

// 表单验证规则
const rules = ref<FormRules>({
    name: [
        { required: true, message: '请输入工作流名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入工作流描述', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
    ],
    category: [
        { required: true, message: '请选择分类', trigger: 'change' }
    ],
    comfyuiJson: [
        { 
            required: true, 
            message: '请配置工作流 JSON',
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请配置工作流 JSON'));
                    return;
                }
                try {
                    const json = typeof value === 'string' ? JSON.parse(value) : value;
                    if (!json || typeof json !== 'object') {
                        callback(new Error('无效的 JSON 格式'));
                        return;
                    }
                    callback();
                } catch (error) {
                    callback(new Error('无效的 JSON 格式'));
                }
            }
        }
    ]
});

// 监听 props 变化
watch(() => props.workflow, (newWorkflow) => {
    if (newWorkflow) {
        formData.value = {
            ...newWorkflow,
            tags: [...(newWorkflow.tags || [])],
            comfyuiJson: newWorkflow.comfyuiJson ? 
                (typeof newWorkflow.comfyuiJson === 'string' ? 
                    newWorkflow.comfyuiJson : 
                    JSON.stringify(newWorkflow.comfyuiJson, null, 2)
                ) : null
        };
        if (formData.value.comfyuiJson) {
            jsonInput.value = formData.value.comfyuiJson as string;
        }
    }
}, { immediate: true, deep: true });

// 处理 JSON 输入
const handleJsonInput = (value: string) => {
    try {
        if (!value) {
            formData.value.comfyuiJson = null;
            jsonError.value = '';
            return;
        }
        const json = JSON.parse(value);
        formData.value.comfyuiJson = json;
        jsonError.value = '';
    } catch (error) {
        jsonError.value = '无效的 JSON 格式';
    }
};

// 处理标签相关操作
const showTagInput = () => {
    inputVisible.value = true;
    nextTick(() => {
        tagInputRef.value?.focus();
    });
};

const handleInputConfirm = () => {
    if (inputValue.value && !formData.value.tags?.includes(inputValue.value)) {
        formData.value.tags = [...(formData.value.tags || []), inputValue.value];
    }
    inputVisible.value = false;
    inputValue.value = '';
};

const handleRemoveTag = (tag: string) => {
    formData.value.tags = formData.value.tags?.filter(t => t !== tag);
};

// 处理预览图上传
const handleThumbnailChange = (file: File) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        formData.value.thumbnail = e.target?.result as string;
    };
    reader.readAsDataURL(file.raw);
};

// 处理表单提交
const handleNext = async () => {
    if (!formRef.value) return;
    
    try {
        await formRef.value.validate();
        emit('next', formData.value);
    } catch (error) {
        console.error('Validate form error:', error);
        ElMessage.error('请检查表单数据');
    }
};

// 取消
const handleCancel = () => {
    emit('cancel');
};
</script>

<style lang="scss" scoped>
.workflow-form {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;

    .thumbnail-uploader {
        :deep(.el-upload) {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: border-color 0.3s;

            &:hover {
                border-color: #409eff;
            }
        }

        .thumbnail-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }

        .thumbnail {
            width: 178px;
            height: 178px;
            display: block;
            object-fit: cover;
        }
    }

    .json-editor {
        position: relative;

        .import-btn {
            position: absolute;
            right: 10px;
            top: -30px;
        }
    }

    .json-error {
        color: #f56c6c;
        font-size: 12px;
        margin-top: 4px;
    }

    .tag-input {
        width: 100px;
        margin-right: 8px;
        vertical-align: bottom;
    }

    .form-help {
        font-size: 12px;
        color: #909399;
        margin-top: 4px;
    }
}
</style>